﻿using FemCloud.Shared;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.IO;
using System.Threading.Tasks;
using DotLiquid;

namespace FemCloud.Server.Controllers
{
    [Route("api/[controller]")]
    public class ElemDataController : Controller
    {
        [HttpGet("forces/{loading}")]
        public IEnumerable<ElemForce> ElemForces(double loading)
        {

            var templateString = @"
finish
/clear

! for loop
itemCount = {{ItemCount}}
{% for i in (1..ItemCount) -%}
item: {{ i }}
{% endfor -%}

/post1
allsel
";

            var template =
                @"
!
! 简支梁受均布荷载
!
finish
/clear

!
load = {{Loading}}

!
b = 0.3
h = 0.2
E = 10e9
I = b*(h**3)/12
A = b*h
!

ndiv = 5

/prep7
k,1,0,0
k,2,5,0
k,3,10,0
l,1,2
l,2,3

!
et,1,beam3
r,1,A,I,h
mp,ex,1,E

!
type,1
mat,1
real,1

lsel,all
lesize,all,,,ndiv,,1
lmesh,all

!
nsel,s,loc,x,0
nsel,r,loc,y,0
d,all,ux
d,all,uy

nsel,s,loc,x,10
nsel,r,loc,y,0
d,all,uy
!

nsel,s,loc,x,5
nsel,r,loc,y,0
f,all,fy,load

!
/solu
allsel
solve

/post1
allsel

!
*get,elemCount,elem,,count
*dim,ms,array,elemCount,3

nn = elnext(0)
*do,i,1,elemCount
    *get,mi_,elem,nn,smisc,6
    *get,mj_,elem,nn,smisc,12
    ms(i,1) = nn
    ms(i,2) = mi_
    ms(i,3) = mj_
    !
    nn = elnext(nn)
*enddo

*cfopen,'elemForce','txt'
*vwrite,ms(1,1),ms(1,2),ms(1,3)
(F3.0,', ',F13.3,', ',F13.3)
*cfclos
";
            //var ansysAppPath = @"C:\Program Files (x86)\Ansys Inc\v100\ANSYS\bin\Intel\ansys100.exe";
            var ansysAppPath = @"C:\Program Files (x86)\Ansys Inc\v100\ANSYS\bin\Intel\ansys.exe";
            var workingDir = @"D:\Code\Gitee\GitRepo\FemCloud\Ansys";
            var projectName = "myProject";

            var resultFileName = "elemForce.txt";
            var outputFileName = "output.txt";

            var templateEngine = Template.Parse(template);
            var ansScripts = templateEngine.Render(Hash.FromAnonymousObject(new { Loading = loading }));

            var ansysScriptFileName = "ansScripts.mac";
            var ansysScriptFilePath = Path.Combine(workingDir, ansysScriptFileName);

            System.IO.File.WriteAllText(ansysScriptFilePath, ansScripts);
            Debug.Assert(System.IO.File.Exists(ansysScriptFilePath));

            var outputFilePath = Path.Combine(workingDir, outputFileName);

            var args = $"-p STRUCT -dir {workingDir} -j {projectName} "
                       + $"-s read -l en-us -b -i {ansysScriptFilePath} -o {outputFilePath}";

            //await Task.Run(() =>
            //{
                var process = new Process
                {
                    StartInfo =
                    {
                        FileName = ansysAppPath,
                        Arguments = args,
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        WindowStyle = ProcessWindowStyle.Hidden,
                    }
                };
                process.Start();
                process.WaitForExit();

                //Thread.Sleep(1000);
            //});

            var resultFilePath = Path.Combine(workingDir, resultFileName);
            Debug.Assert(System.IO.File.Exists(resultFilePath));

            var lines = System.IO.File.ReadAllLines(resultFilePath);
            Debug.Assert(lines.Length > 0);
            var elemForces = lines.Select(line =>
            {
                var tokens = line.Trim().Split(',');
                Debug.Assert(tokens.Length == 3);

                int.TryParse(tokens[0].Trim().TrimEnd('.'), out var elemNum);
                double.TryParse(tokens[1].Trim(), out var mi);
                double.TryParse(tokens[2].Trim(), out var mj);

                return new ElemForce()
                {
                    ElemNum = elemNum,
                    Mi = mi,
                    Mj = mj,
                };
            });
            return elemForces;
        }
    }
}
